public class LinkedListDisplay {
    public static void main(String[] args) {
        //1、初始化链表 1 -> 3 -> 2 -> 5 -> 4
        ListNode node0 = new ListNode(1);  //初始化各个链表节点
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(5);
        ListNode node4 = new ListNode(4);

        node0.next = node1;  //构建节点之间的引用
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        //获取第index节点的值
        int valueByIndex = getValueByIndex(3, node0);
        System.out.println(valueByIndex);
    }

    //1、按顺序打印链表
    public static void display(ListNode headNode){
        System.out.println("链表展示：");
        ListNode currentNode = headNode;
        while (currentNode != null){
            System.out.print(currentNode.val);
            if(currentNode.next != null){
                System.out.print("->");
            }
            currentNode = currentNode.next;
        }
    }

    //2、获取第index节点的值
    public static int getValueByIndex(int index, ListNode headNode) {
        //处理异常情况 - 空链表、越界
        int[] linkedListArray = LinkedListToArray.linkedListToArray(headNode);
        int size = linkedListArray.length; //获得链表长度
        if(index > size || headNode == null){
            System.out.println("越界 或 空链表");
            return -1;
        }
        //正常遍历 - 获得第index节点的值
        ListNode currentNode = headNode;
        for (int i = 0; i < index; i++) {
            currentNode = currentNode.next;
        }
        return currentNode.val;
    }
}
